# -*- coding: utf-8 -*-
# !/usr/bin/env python
import yaml
from rest_framework.views import APIView
from components.kubernetes.api_file_verify import get_info
from utils.K8S import K8sApi
from utils.views import Result, ReturnClass
from copy import deepcopy


class SyncDeploymentYaml(APIView):
    def put(self, request):
        data = request.data
        old_kubernetes_cluster_id = data['old_kubernetes_cluster_id']
        now_kubernetes_cluster_id = data['now_kubernetes_cluster_id']
        old_kubernetes_cluster_namespace = data['old_kubernetes_cluster_namespace']
        now_kubernetes_cluster_namespace = data['now_kubernetes_cluster_namespace']
        if_create = data['if_create']
        data_ = data['data']


        old_return_info = get_info(old_kubernetes_cluster_id)
        if ReturnClass.if_ok(old_return_info):
            old_kubernetes_cluster_sign_kubeconfig = ReturnClass.get_value(old_return_info)
        else:
            return Result.fail_response(ReturnClass.get_value(old_return_info))

        now_return_info = get_info(now_kubernetes_cluster_id)
        if ReturnClass.if_ok(now_return_info):
            now_kubernetes_cluster_sign_kubeconfig = ReturnClass.get_value(now_return_info)
        else:
            return Result.fail_response(ReturnClass.get_value(now_return_info))

        now_k8s_api = K8sApi(now_kubernetes_cluster_sign_kubeconfig)
        old_k8s_api = K8sApi(old_kubernetes_cluster_sign_kubeconfig)

        yaml_date = []
        for data_one in data_:
            one_deployment_dict_info = old_k8s_api.get_deployment_yaml(data_one['old_version_pod_name'], old_kubernetes_cluster_namespace)
            one_deployment_dict_info['metadata']['namespace'] = now_kubernetes_cluster_namespace
            # one_deployment_str_yaml_info = yaml.safe_load(yaml.dump(one_deployment_dict_info, ))
            # yaml_date.append(one_deployment_str_yaml_info)
            one_deployment_dict_info['metadata'].pop('resourceVersion')

            if if_create:
                yaml_date.append(one_deployment_dict_info)
            else:
                pass

        # now_k8s_api.update_deployment_yaml(, one_deployment_dict_info)
        try:
            now_k8s_api.create_exec_ymal(yaml_date)
        except Exception as e:
            return Result.fail_response(msg=str(e))

            # now_k8s_api.
        # try:
        #     now_data = now_k8s_api.get_namespaced_deployment(now_version_cluster_select_name)
        #     old_data = old_k8s_api.get_namespaced_deployment(old_version_cluster_select_name)
        #
        # except Exception as e:
        #     return Result.fail_response(msg=str(e))
        return Result.success_response(data="同步成功", msg='执行成功')
